<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-10-13
 * Time: 10:30:06
 * Info: 前端页面控制器
 */

namespace plugin\huiblog\app\controller;

use plugin\huiblog\app\model\ArticleCate;
use support\Request;
use think\facade\Db;
use support\View;
use plugin\huiblog\app\model\Keywords as KeywordsModel;
use plugin\huiblog\app\model\Article as ArticleModel;
use plugin\huiblog\app\model\Action as ActionModel;
use plugin\huiblog\app\model\Nav as NavModel;

class IndexController
{

    /**
     * 控制器不需要鉴权
     * @var bool
     */
    public $noNeedAuthController = true;

    protected $template = '';

    protected $__STATIC__ = '';

    protected $indexUrl = '';

    public function __construct()
    {
        $configTemplate   = get_blog_config('web', 'template');
        $this->template   = "index/".$configTemplate ?? 'default';
        $this->__STATIC__ = "/app/".request()->plugin."/".$configTemplate."/";
        $this->indexUrl   = "/blog";
        // 控制器初始化
        $this->initialize();
    }

    //公共模版赋值参数
    protected function initialize()
    {
        $uri           = request()->uri();
        $navList       = (new NavModel())->getNavs('NAV_HOME');
        $navListIdName = array_column($navList, 'id', 'src');

        $seo            = (get_blog_config('web'));
        $seo['action']  = request()->action;
        $cateId         = $navListIdName[$uri] ?? 0;
        $seo['cate_id'] = $cateId;

        View::assign([
            'COMMON_NAV' => $navList,
            '__STATIC__' => $this->__STATIC__,
            'index_url'  => $this->indexUrl,
            'seo'        => $seo,
            'blog'       => get_blog_config('blog'),
            'uri'        => $uri,
            'cate_id'    => $cateId
        ]);
    }

    /**
     * 前台首页
     */
    public function index()
    {
        //博客统计信息
        $blog      = get_blog_config('blog');
        $startdate = strtotime($blog['create_time']);
        $nowtime   = date('Y-m-d', time());
        $enddate   = strtotime($nowtime);
        $counts    = [
            'article' => (new ArticleModel())->count(),
            'action'  => 0,
            'days'    => round(($enddate - $startdate) / 3600 / 24)
        ];
        $book      = [];

        //判断轮播图插件是否存在（查询表结构：cmf_slide是否存在）
        $slide_sql = count(Db::query("SHOW TABLES LIKE 'cmf_slide'"));
        if ( ! $slide_sql) {
            return "请先安装轮播【slide】插件";
        }

        $returnData = [
            'search_keywords' => (new KeywordsModel())->search_key(),
            'hot_tag'         => (new KeywordsModel())->tags(20),
            'action'          => (new ActionModel())->lists(7),
            'book'            => $book,
            'counts'          => $counts,
        ];

        return view($this->template.'/index', $returnData);
    }

    /**
     * 文章列表页
     * @return void
     */
    public function lists(Request $request)
    {
        $cid = $request->get('cate_id');
        $tid = $request->get('tag_id');

        $returnData = ['cid' => $cid, 'tid' => $tid];

        return view($this->template.'/lists', $returnData);
    }

    /**
     * 搜索页列表
     *
     * @param Request $request
     */
    public function search(Request $request)
    {
        $keyword    = $request->get('keyword');
        $returnData = [
            'keyword' => $keyword
        ];

        return view($this->template.'/search', $returnData);
    }

    /**
     * 和文章有关的页面
     */
    public function article($request, $id)
    {
        $detail = Db::table('blog_article')->where(['status' => 1])->find($id);
        if (empty($detail)) {
            return "获取数据失败";
        }
        //更新阅读量
        Db::table('blog_article')->where('id', $id)->inc('read')->update();

        //关键字
        $keyword_array = Db::table('blog_article_keywords')->field('k.id,k.title')->alias('a')->leftJoin(['blog_keywords' => 'k'],
            'k.id = a.keywords_id')->where(array(
            'a.aid'    => $id,
            'k.status' => 1
        ))->limit(5)->select()->toArray();
        foreach ($keyword_array as $key => $keyword) {
            $keyword_array[$key]['url'] = "/blog/lists?tag_id=".$keyword['id'];
        }

        $detail['keyword_array'] = $keyword_array;

        return view($this->template.'/article', ['detail' => $detail]);
    }

    /**
     * 博主动态页面
     */
    public function actions()
    {
        $returnData = [
            'hot_articles' => (new ArticleModel())->hotArtices(),
        ];

        return view($this->template.'/actions', $returnData);
    }

    /**
     * 文章归档
     */
    public function archives()
    {
        $cate_count    = (new ArticleCate)->count();
        $tag_count     = (new KeywordsModel())->count();
        $article_count = (new ArticleModel)->count();
        $view_count    = 0;
        $read_count    = 0;

        $article        = Db::table('blog_article')->where(['status' => 1])->field('id,title,read,create_time')->order('id desc')->select()->toArray();
        $month_archives = blog_month_document($article);
        $year_archives  = blog_year_document($month_archives);
        $date_archives  = blog_date_document($article);

        $returnData = [
            'cate_count'    => $cate_count,
            'tag_count'     => $tag_count,
            'article_count' => $article_count,
            'view_count'    => $view_count,
            'read_count'    => $read_count,
            'year_archives' => $year_archives,
            'date_archives' => json_encode($date_archives),
        ];

        return view($this->template.'/archives', $returnData);
    }

}
